<template>
  <GroupPage
    :search-form-props="{
      keywordSearchData: keywordSearchKeys,
      columns: grpColumns,
      title: t('routes.messageTemplate'),
      addBtnText: t('aiot.msgTemp.addGrp'),
      delBtnText: t('aiot.msgTemp.delGrp'),
      addBtnOperType: OperPermissionType.MANAGE,
      delBtnOperType: OperPermissionType.MANAGE,
      delBtnProps: {
        disabled: !curSelectedGrp,
        onClick: handleDelFn,
      },
    }"
    :group-title="t('aiot.msgTemp.grpList')"
    :content-title="t('aiot.msgTemp.msgTempList', { length: pagination ? pagination.total : 0 })"
    @add="setGrpShowOptions({ action: CURDAction.CREATE })"
    @search="onSearchGroup"
  >
    <template #extraButtons>
      <PermissionBtn
        :oper-type="OperPermissionType.MANAGE"
        class="mr-4.5"
        :disabled="!curSelectedGrp"
        @click="setGrpShowOptions({ action: CURDAction.UPDATE })"
      >
        {{ t("aiot.msgTemp.updateGrp") }}
        <template #icon>
          <Icon type="icon-bianji" class="text-color-secondary" />
        </template>
      </PermissionBtn>
    </template>
    <template #group>
      <SpinSkeleton v-show="grpData.length > 0" :loading="grpLoading">
        <div class="flex flex-row flex-wrap items-center lg:block lg:flex-nowrap">
          <div
            v-for="(el, i) in grpData"
            :key="el.messageTemplateGroupName"
            class="py-2 px-4 mb-2 cursor-pointer mr-2 lg:mr-0"
            :class="[curIndex === i ? 'bg-opacity-10 bg-color-active' : 'bg-header']"
            @click="handleCheckModal(el, i)"
          >
            <div class="mb-1" :class="[curIndex === i ? 'text-color-active' : 'text-color-main']">
              {{ el.messageTemplateGroupName }}
            </div>
            <div
              :title="el.pushBusinessType"
              class="text-color-secondary text-sm overflow-hidden text-ellipsis whitespace-nowrap"
              >{{ el.pushBusinessType ? pushBusinessTypeList[el.pushBusinessType] || "-" : "-" }}</div
            >
          </div>
        </div>
      </SpinSkeleton>
      <SlEmpty v-show="!grpLoading && grpData.length === 0" :description="emptyText"></SlEmpty>
    </template>
    <template #content>
      <SearchForm
        ref="searchModalRef"
        v-model:columns="columns"
        class="mb-0 mx-7 mt-6"
        :add-btn-text="t('aiot.msgTemp.addMsgTemp')"
        :keyword-search-data="searchModel"
        :required-keys="requiredKeys"
        :select-data="selectData"
        :add-btn-oper-type="OperPermissionType.MANAGE"
        @add="showCreateModal"
        @search="handleSearch"
      />
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="mx-7 sl-pagination-px0"
          :columns="columns"
          row-key="messageTemplateId"
          :data-source="tableData"
          :loading="tableLoading"
          :pagination="pagination"
          :scroll="{ x: false }"
          :search-model="msgTempSearchModel"
        >
          <template #bodyCell="{ column, record }">
            <a-space v-if="column.key === 'oper'">
              <PermissionBtn
                :btn-props="{ type: 'link' }"
                :oper-type="OperPermissionType.MANAGE"
                @click="showUpdateModal(record)"
                >{{ t("common.edit") }}</PermissionBtn
              >
              <PermissionBtn
                :btn-props="{ type: 'link', danger: true }"
                :oper-type="OperPermissionType.MANAGE"
                @click="deleteRecord(record)"
                >{{ t("common.delete") }}</PermissionBtn
              >
            </a-space>
            <EllipsisText v-if="column.dataIndex === 'templateCode'" :max-len="10" :text="record.templateCode" />
            <div v-if="column.key === 'notifyType'">
              {{ getLabelByValueFromEnum(record.notifyType, NotifyType, "msgTempNotifyType") }}
            </div>
            <div v-if="column.key === 'messageType'">
              {{ getLabelByValueFromEnum(record.messageType, MessageType, "msgTempType") }}
            </div>
            <pre v-if="column.dataIndex === 'templateContent'" v-html="record.templateContent"></pre>
          </template>
        </SlTable>
      </div>
    </template>
    <CURDDialog
      ref="grpIns"
      :create-title="t('aiot.msgTemp.addGrp')"
      :update-title="t('aiot.msgTemp.updateGrp')"
      :delete-message="t('aiot.msgTemp.delGrpMsg')"
      :show-options="grpShowOptions"
      :columns="grpColumns"
      :model="grpModel"
      :model-form-setting="gropModelFormSetting"
      :table-data="grpData"
      :curd="grpCurd"
      id-key="messageTemplateGroupId"
      :reload-table="grpReloadTable"
    />

    <CURDDialog
      id-key="messageTemplateId"
      :columns="columns"
      :create-title="t('aiot.msgTemp.addMsgTemp')"
      :update-title="t('aiot.msgTemp.updateMsgTemp')"
      :check-title="t('aiot.msgTemp.msgTempDetail')"
      :delete-message="t('aiot.msgTemp.delMsg')"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :oper-data="operData"
      :curd="curd"
      :reload-table="reloadTable"
      @before-ok="functionBeforeOk"
      @before-show="beforeShow"
    />
  </GroupPage>
</template>
<script lang="ts" setup>
import { h, onMounted, ref, shallowRef, watch } from "vue";
import { useI18n } from "/@/locales/useI18n";
import { useCURD } from "/@/hooks/useCURD";
import { Api, getPushBusinessTypeMaps } from "/@/api/aiot/messageTemplate";
import SearchForm from "/@/components/SearchForm.vue";
import Icon from "/@/components/Icon.vue";
import SlEmpty from "/@/components/SlEmpty.vue";
import GroupPage from "/@/components/GroupPage.vue";
import PermissionBtn from "/@/components/PermissionBtn.vue";
import { OperPermissionType } from "/@/api/aiot/role/models";
import {
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
  CURDAction,
  CURDDialogExpose,
  OperItem,
  CURDModalEvent,
} from "/@/components/CURDDialog/models";
import SpinSkeleton from "/@/components/common/SpinSkeleton.vue";
import SlTable from "/@/components/SlTable.vue";
import { MessageType, MsgTempGrpItem, MsgTempItem, NotifyType } from "/@/api/aiot/messageTemplate/models";
import { SelectItem } from "/@/types/components";
import EllipsisText from "/@/components/common/EllipsisText.vue";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import type { TableColumnProps } from "ant-design-vue";
import { useEmptyText } from "/@/hooks/useEmptyText";
import { OrderRule } from "/@/api/models";
const { t } = useI18n();
const grpColumns = [
  { title: t("aiot.msgTemp.messageTemplateGroupName"), dataIndex: "brandGroupName", ellipsis: true, width: "80px" },
  { title: t("aiot.msgTemp.pushBusinessType"), dataIndex: "description", ellipsis: true, width: "80px" },
  { title: t("common.oper"), key: "oper", width: "80px" },
];
const curIndex = ref(-1);
const searchModalRef = ref();
const keywordSearchKeys = [{ label: t("aiot.msgTemp.messageTemplateGroupName"), key: "searchText" }];
const {
  curd: grpCurd,
  tableData: grpData,
  tableLoading: grpLoading,
  reloadTable: grpReloadTable,
  searchModel: grpSearchModel,
} = useCURD<MsgTempGrpItem>({
  getDataUrl: Api.getMessageTemplateGroups,
  createUrl: Api.addMessageTemplateGroup,
  updateUrl: Api.updateMessageTemplateGroup,
  deleteUrl: Api.deleteMessageTemplateGroupByIds,
  loadOnMounted: false,
});
const requiredKeys = ["messageTemplateName", "messageType", "notifyType", "oper"];
const grpShowOptions = shallowRef<ShowCURDModalOptions>();
const pushBusList = ref<Array<SelectItem>>([]);
const grpModel = ref<MsgTempGrpItem>({
  messageTemplateGroupName: "",
  pushBusinessType: "",
});
const { emptyText, modelForEmptyText } = useEmptyText();
watch(
  grpSearchModel,
  (v) => {
    modelForEmptyText.value = v;
  },
  { deep: true }
);
// 删除按钮
function handleDelFn() {
  setGrpShowOptions({ action: CURDAction.DELETE, record: curSelectedGrp.value });
}
function handleCheckModal(el, i) {
  curIndex.value = i;
  searchModalRef.value.clearKeyword();
  grpIns.value?.isOpen() && setGrpShowOptions({ action: CURDAction.UPDATE, record: el });
}
// 查询模板组数据
async function onSearchGroup(model) {
  await grpReloadTable({ ...model, sort: "createdOn", order: OrderRule.DESC });
  handleIndexChange(0);
}
// 删除分组初始化选择第一条数据
watch(
  () => grpData.value,
  () => {
    handleIndexChange(0);
  }
);
const pushBusinessTypeList = ref([]);
const gropModelFormSetting: FormItemData[] = [
  {
    key: "messageTemplateGroupName",
    label: t("aiot.msgTemp.messageTemplateGroupName"),
    max: 32,
    required: true,
  },
  {
    key: "pushBusinessType",
    label: t("aiot.msgTemp.pushBusinessType"),
    type: FormItemComponentType.SELECT,
    async getData() {
      const data = await getPushBusinessTypeMaps();
      pushBusinessTypeList.value = data;
      let keys = Object.keys(data);
      return keys
        ? keys.map((key) => ({
            label: data[key],
            value: key,
          }))
        : [];
    },
    props: {
      options: [],
      getPopupContainer(node) {
        return node.parentNode;
      },
    },
  },
];
function setGrpShowOptions(options: ShowCURDModalOptions) {
  grpShowOptions.value = options;
  if (options.action === "UPDATE") {
    gropModelFormSetting[1].hide = true;
    // 更新当前所选数据
    curSelectedGrp.value = grpData.value[curIndex.value];
    grpShowOptions.value.record = curSelectedGrp.value;
  } else {
    gropModelFormSetting[1].hide = false;
  }
}
const curSelectedGrp = shallowRef<MsgTempGrpItem>();
function handleIndexChange(index) {
  const grp = grpData.value[index];
  curIndex.value = index;
  curSelectedGrp.value = grp;
  if (grp) {
    //根据所选分组 刷新品牌数据
    reloadTable({
      model: {
        messageTemplateGroupId: grp.messageTemplateGroupId,
        searchText: "",
      },
    });
  } else {
    tableData.value = [];
  }
}
watch(curIndex, handleIndexChange);
onMounted(async () => {
  await grpReloadTable({ searchText: "", sort: "createdOn", order: OrderRule.DESC });
  let req = await getPushBusinessTypeMaps();
  pushBusinessTypeList.value = req;
  let keys = Object.keys(req);
  pushBusList.value =
    keys?.map((key) => ({
      label: req[key],
      value: key,
      key,
    })) || [];
});
/**
 * 用户
 */
//用户窗口实例
const grpIns = ref<CURDDialogExpose>();
const columns = ref<TableColumnProps<MsgTempGrpItem>[]>([
  {
    title: t("aiot.msgTemp.messageTemplateName"),
    dataIndex: "messageTemplateName",
  },
  {
    title: t("aiot.msgTemp.messageType"),
    dataIndex: "messageType",
  },
  {
    title: t("aiot.msgTemp.notifyType"),
    dataIndex: "notifyType",
  },
  {
    title: t("aiot.msgTemp.templateCode"),
    dataIndex: "templateCode",
  },
  {
    title: t("aiot.msgTemp.templateContent"),
    dataIndex: "templateContent",
  },
  {
    title: t("aiot.msgTemp.handlerParams"),
    dataIndex: "handlerParams",
  },
  {
    title: t("aiot.msgTemp.handlerUrl"),
    dataIndex: "handlerUrl",
  },
  {
    title: t("aiot.msgTemp.wechatMiniAppid"),
    dataIndex: "wechatMiniAppid",
  },
  {
    title: t("aiot.msgTemp.wechatMiniPagePath"),
    dataIndex: "wechatMiniPagePath",
  },
  {
    title: t("common.oper"),
    key: "oper",
  },
]);
const model = ref<MsgTempItem>({
  messageTemplateName: "",
  messageType: "",
  notifyType: "",
  templateCode: "",
  templateContent: "",
  handlerParams: "",
  handlerUrl: "",
  wechatMiniAppid: "",
  wechatMiniPagePath: "",
});
const modelFormSetting: FormItemData[] = [
  {
    key: "messageTemplateName",
    label: t("aiot.msgTemp.messageTemplateName"),
    max: 32,
    required: true,
  },
  {
    key: "messageType",
    label: t("aiot.msgTemp.messageType"),
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(MessageType, "msgTempType"),
    },
  },
  {
    key: "notifyType",
    label: t("aiot.msgTemp.notifyType"),
    required: true,
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(NotifyType, "msgTempNotifyType"),
    },
  },
  {
    key: "templateCode",
    label: t("aiot.msgTemp.templateCode"),
    required: true,
    max: 64,
  },
  {
    key: "templateContent",
    label: t("aiot.msgTemp.templateContent"),
    max: 250,
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "handlerParams",
    label: t("aiot.msgTemp.handlerParams"),
    max: 32,
  },
  {
    key: "handlerUrl",
    label: t("aiot.msgTemp.handlerUrl"),
    max: 32,
  },
  {
    key: "wechatMiniAppid",
    label: t("aiot.msgTemp.wechatMiniAppid"),
    max: 32,
  },
  {
    key: "wechatMiniPagePath",
    label: t("aiot.msgTemp.wechatMiniPagePath"),
    max: 32,
  },
];
// 搜索select下拉数据
const selectData = ref<SelectItem[]>([
  {
    label: t("aiot.msgTemp.messageType"),
    value: "",
    key: "messageType",
    props: { allowClear: true },
    options: enumToOptions(MessageType, "msgTempType"),
  },
  {
    label: t("aiot.msgTemp.notifyType"),
    value: "",
    props: { allowClear: true },
    key: "notifyType",
    options: enumToOptions(NotifyType, "msgTempNotifyType"),
  },
]);
const showOptions = ref<ShowCURDModalOptions>();
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function beforeShow(e) {
  if (e.action === CURDAction.UPDATE || e.action === CURDAction.CHECK) {
  }
}
const searchModel = [{ key: "searchText", label: t("aiot.msgTemp.messageTemplateName") }];
function handleSearch(model) {
  reloadTable({ model, current: 1 });
}
const {
  tableData,
  tableLoading,
  curd,
  reloadTable,
  pagination,
  searchModel: msgTempSearchModel,
} = useCURD<MsgTempItem>({
  createUrl: Api.addMessageTemplates,
  deleteUrl: Api.deleteMessageTemplatesByIds,
  getPageUrl: Api.getMsgTempPage,
  updateUrl: Api.updateMessageTemplates,
});

const operData: OperItem<MsgTempItem>[] = [
  {
    label: t("common.edit"),
    handler: showUpdateModal,
  },
  {
    label: t("common.delete"),
    type: "primary",
    danger: true,
    handler: deleteRecord,
  },
];
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function deleteRecord(record) {
  showOptions.value = { action: CURDAction.DELETE, record };
}
function functionBeforeOk(e: CURDModalEvent) {
  if (e.model) {
    const model = e.model as MsgTempItem;
    if (e.action === CURDAction.CREATE) {
      model.messageTemplateGroupId = curSelectedGrp.value?.messageTemplateGroupId
        ? curSelectedGrp.value.messageTemplateGroupId
        : "";
    }
  }
}
</script>
